﻿using System;
using System.Globalization;
using System.Linq;
using SuperSimpleWebshop.Common;
using SuperSimpleWebshop.Domain;
using SuperSimpleWebshop.Domain.Helpers;
using SuperSimpleWebshop.Domain.Interfaces;
using SuperSimpleWebshop.Domain.Repositories;
using umbraco;
using umbraco.presentation.nodeFactory;
using System.Threading;

namespace SuperSimpleWebshop.Payment.PayPal
{
    /// <summary>
    /// Create request to Payment Provider API
    /// </summary>
    public class PayPalPaymentRequestHandler : IPaymentRequestHandler
    {
        #region IPaymentRequestHandler Members
        /// <summary>
        /// Gets the payment provider name
        /// </summary>
        /// <returns>Name of the payment provider</returns>
        public string GetName()
        {
            return "PayPal";
        }

        /// <summary>
        /// Creates a payment request for this payment provider
        /// </summary>
        /// <param name="order">Order to base the payment request on</param>
        /// <returns>Payment request</returns>
        public PaymentRequest CreatePaymentRequest(Order order)
        {
            var helper = new PaymentConfigHelper(order.OrderInfo.PaymentInfo.PaymentProviderName);

            var paymentProvider = new OrderRepository().GetAllPaymentProviders().Where(x => x.Name == order.OrderInfo.PaymentInfo.PaymentProviderName).FirstOrDefault();

            var request = new PaymentRequest();
            request.Parameters.Add("cmd", "_xclick");

            // retrieve Account ID
            request.Parameters.Add("business", helper.Settings["accountId"]);

            //request.Parameters.Add("invoice", order.OrderInfo.OrderNumber.ToString());
            request.Parameters.Add("invoice", order.Document.Text);
            CultureInfo ci = new CultureInfo("en-US");
            var totalAmountAsString = OrderHelper.GetTotalAmountUsingVATCheck().ToString("N", ci);
            request.Parameters.Add("amount", totalAmountAsString);
            request.Parameters.Add("tax_cart", totalAmountAsString);
            request.Parameters.Add("no_note", "0");
            request.Parameters.Add("currency_code", order.OrderInfo.ShopAlias.CurrencyCode);
            request.Parameters.Add("lc", order.OrderInfo.CultureInfo.TwoLetterISOLanguageName);

            var baseUrl = string.Format("http://{0}", library.GetCurrentDomains(Node.GetCurrent().Id).First().Name);
            baseUrl = baseUrl.Substring(0, baseUrl.LastIndexOf("/"));

            var oldUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
            var oldCulture = System.Threading.Thread.CurrentThread.CurrentCulture;

            var shopAliasNode = ShopAliasHelper.GetAllShopAlias().Where(x => x.Name.ToLower() == order.OrderInfo.ShopAlias.Alias.ToLower()).FirstOrDefault();

            Thread.CurrentThread.CurrentCulture = shopAliasNode.CultureInfo;
            Thread.CurrentThread.CurrentUICulture = shopAliasNode.CultureInfo;
            
            var nodeId = DomainHelper.GetNodeIdForDocument("sswsOrderProcessNode", library.GetDictionaryItem("PaymentConfirmation"), ShopAliasHelper.GetCurrentShopAlias());

            Thread.CurrentThread.CurrentCulture = shopAliasNode.CultureInfo;
            Thread.CurrentThread.CurrentUICulture = shopAliasNode.CultureInfo;

            var returnUrl = string.Format("{0}{1}", baseUrl, library.NiceUrl(nodeId));
            request.Parameters.Add("return", returnUrl);

            request.Parameters.Add("shopping_url", string.Format("{0}/{1}", baseUrl, "shop"));

            string reportUrl = string.Format("{0}{1}", baseUrl, library.NiceUrl(paymentProvider.Id));
            request.Parameters.Add("notify_url", reportUrl);

            #region testmode
            ///
            /// check if provider is in testmode
            ///         
            if (!helper.TestModeEnabled)
            {
                request.Parameters.Add("cn", "Test");
            }
            #endregion

            // Order as shown with PayPal
            request.Parameters.Add("item_name", order.Document.Text);

            // Set GUID to identify order in SSWS
            // Sent GUID for identification to PayPal
            // PayPal will return custom value to validate order
            order.OrderInfo.PaymentInfo.PaymentTransactionId = Guid.NewGuid().ToString();
            request.Parameters.Add("custom", order.OrderInfo.PaymentInfo.PaymentTransactionId.ToString());

            order.OrderInfo.PaymentInfo.PaymentParameterRenderMethod = PaymentParameterRenderMethod.QueryString;

            #region URLforTestMode
            // check if provider is in testmode to send request to right URL

            if (helper.TestModeEnabled)
            {
                request.PaymentUrlBase = helper.Settings["testURL"];
            }
            else
            {
                request.PaymentUrlBase = helper.Settings["url"];
            }
            #endregion

            order.OrderInfo.PaymentInfo.PaymentURL = request.PaymentUrl;
            order.OrderInfo.PaymentInfo.PaymentParameters = request.ParametersAsString;

            return request;
        }
        #endregion
    }
}
